//      module.c
//      
//      Copyright 2012 Mukesh <mukesh_fun2010@yahoo.in>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.


#include "module.h"

gchar * gesbian_modules [] = {
	"filesystem",
	NULL
} ;

gchar * gesbian_modules_paths [] = {
	"/usr/lib/gesbian/plugins",
	"/usr/local/lib/gesbian/plugins",
	NULL
} ;


gchar * gesbian_module_find ( GesbianModules module )
{
	in ;
	
	gchar * cd = g_get_current_dir () ;
	gchar * filename = g_strdup_printf ( 	"%s/plugins/%s.so",
											cd,
											gesbian_modules [module] ) ;
	
	g_free ( cd ) ;

	if ( ! g_file_test ( filename, G_FILE_TEST_EXISTS ))
	{
		g_free ( filename ) ;
		
		gint i = 0 ;
		
		while ( gesbian_modules_paths [i] != NULL )
		{
			filename = g_strdup_printf ( 	"%s/%s.so",
											gesbian_modules_paths [i],
											gesbian_modules [module] ) ;
			
			if ( g_file_test ( filename, G_FILE_TEST_EXISTS ))
				break ;
			
			g_free ( filename ) ;
			g_nullify_pointer ( & filename ) ;
			
			i ++ ;
		}
		
	}
	
	out ;
	return filename ;
}

GesbianModule * gesbian_module_load ( GesbianPlugin * g, GesbianModules module )
{
	in ;
	if ( ! g_module_supported ())
	{
		g_critical ( "%s: Cannot load module: %s",
						__func__,
						g_module_error ()) ;
	
		out ;
		return ;
	}
	
	
	gchar * filename = gesbian_module_find ( module ) ;
	
	if ( filename == NULL )
	{
		g_critical ( "%s: Cannot find module !", __func__ ) ;
		out ;
		
		return ;
	}
	
	GModule * mod = g_module_open ( filename, G_MODULE_BIND_LAZY ) ;
	g_free ( filename ) ;
	
	if ( mod == NULL )
		g_critical ( "%s: Cannot open module: %s !", __func__, g_module_error ()) ;
	
	GesbianModule * gmod = g_slice_new ( GesbianModule ) ;
	gmod -> module = mod ;
	
	g_module_symbol ( mod, "gesbian_plugin_init", & gmod -> init ) ;
	g_module_symbol ( mod, "gesbian_plugin_uri_open", & gmod -> open ) ;
	
	gmod -> init ( g ) ;
	
	out;
	return gmod ;
}
